#pragma once

#include <QString>
#include <QNetworkAccessManager>
#include <QObject>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QEventLoop>
#include "except.hpp"
#include "log.hpp"

namespace cloud
{

extern QString default_svr_addr;

class HttpConn : public QObject
{
    Q_OBJECT
public:
    HttpConn(const QString& addr = default_svr_addr)
        : _svr_addr(addr)
        , _manager(new QNetworkAccessManager(this))
    {}

    QByteArray request(const QUrl& url)
    {

        QNetworkReply* reply = _manager->get(QNetworkRequest(url));

        // sync io
        QEventLoop loop;
        connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
        loop.exec();

        reply->deleteLater();
        if (reply->error() != reply->NoError)
        {
            WARN("request times, but response is error");
            return "";
        }
        else
        {
            return reply->readAll();
        }
    }
public:
    QString _svr_addr;

private:
    QNetworkAccessManager* _manager;
};

}
